<template>
  <view class="container">
    <!-- <image class="container_bg" src="https://bw000.zjjqf.cn/file/000upload/image/home_bg.png" mode="widthFix" /> -->
    <custom-navbar :immersive="immersive" :color="titleColor" title="社发配送" :showBack="false"> </custom-navbar>
    <view class="container_header" :style="{ paddingTop: `${navbarHeight}px` }">
      <view class="container_header_location" @click.prevent="goWarehouse">
        <uni-icons type="location-filled" color="white" size="18" />
        <view class="container_header_location_name">{{ warehouseInfo.name ? warehouseInfo.name : '未获取到定位' }}</view>
        <uni-icons type="right" color="white" size="16" />
      </view>
      <view style="position: relative">
        <locationDialog :showTip.sync="showTip"></locationDialog>
      </view>
    </view>
    <view class="container_type-btn" @click="goShop"> <image src="/static/image/home_btn.png" mode="widthFix" /> </view>
    <view class="container_middle">
      <view class="container_middle_row">
        <view class="container_middle_row_item" v-for="(item, index) in typeList" :key="index" @click="goDetail(item)">
          <view class="container_middle_row_item_icon"> <image :src="item.icon" mode="widthFix" /></view>
          <view>{{ item.name }}</view>
        </view>
      </view>
      <view class="container_middle_row" style="margin-top: 32rpx">
        <view class="container_middle_row_item" v-for="(item, index) in goodsTypeList" :key="index" @click="goShop(item)">
          <view class="container_middle_row_item_categry"> <image :src="item.imageUrl" /></view>
          <view>{{ item.name }}</view>
        </view>
      </view>
    </view>

    <view class="container_pic-2">
      <image src="https://bw000.zjjqf.cn/file/000upload/image/home_pic_2.png" mode="widthFix" />
    </view>

 

    <view class="container_coupon" @click="receiveCoupon">
      <image src="https://bw000.zjjqf.cn/file/000upload/image/home_coupon_pic.png" mode="widthFix" />
    </view>

    <view class="container_recommand">
      <view class="container_recommand_pic"><image src="/static/image/home_recommand_icon.png" mode="widthFix" /></view>

      <uni-grid :column="2" :highlight="true" :showBorder="false" :square="false">
        <uni-grid-item v-for="(item, index) in recommendGoods" :index="index" :key="index" style="padding: 10rpx 0">
          <view class="container_recommand_item">
            <view class="container_recommand_item_pic"> <image :src="item.image" mode="aspectFill" @click="goItemDetail(item)" /> </view>

            <view class="container_recommand_item_title">
              {{ item.goodsName }}
            </view>
            <view class="container_recommand_item_money">
              <itemPrice :price="item.taxPrice"></itemPrice>
              <image src="/static/image/cart_icon.png" mode="widthFix" @click="selectGoods(item)" />
            </view>
          </view>
        </uni-grid-item>
      </uni-grid>
    </view>

    <uni-popup ref="popup" background-color="#fff">
      <view class="pop-pic"><image :src="codeImg" mode="widthFix" show-menu-by-longpress /></view>
    </uni-popup>
  </view>
</template>

<script>
import { getBasGoodsTypeTree } from '../../service/api/dropDown'
import { basGoodsListForAdd, getDict } from '../../service/api/shopping'

import { appletExtraDict, collect, customerUnCollectCouponList } from '../../service/api/home'
import { getOpenId, setImage, setOpenId, setSessionKey, setToken, setUserInfo, getUserInfo } from '../../service/auth'
import { getLoginOpenId } from '../../service/api/wx'
import couponPopup from '../../components/couponPopup'
import { getQRCode } from '@/service/api/mine'

import navbarMixin from '@/mxins/navbar.js'

import { getBasWarehouseList } from '@/service/api/logistics'
import locationDialog from '@/components/location_dialog'

import recommandItem from '@/components/recommandItem'
import itemPrice from '@/components/itemPrice'
import { wxLogin } from '@/service/api/login.js'
import SaveImageUtil from '@/utils/saveImageUtil'
import { apiBaseUrl } from '@/service/config.js'
import { mapState, mapGetters, mapMutations } from 'vuex'
export default {
  name: 'home',
  mixins: [navbarMixin],
  components: { couponPopup, locationDialog, recommandItem, itemPrice },
  data() {
    return {
      goodsTypeList: [],
      customerId: '',
      currentGoods: {},
      selectedGoodsList: [],
      noticeList: ['通知1', '通知2', '通知3'],
      showCouponBox: false,
      mask: false,
      user: {},
      query: {
        page: 1,
        size: 20,
        goodsTypeIds: '',
        type: 'SALE',
        isIgnoreZeroUnGiftGoodsCount: 1,
        isAppletSale: 1,
        scope: 0,
        ignoreGoodsTagNames: '回瓶回箱,瓶盖',
        isRecommend: '1',
      },
      currentPromotionId: -1,
      recommendGoods: [],
      unCollectCouponList: [],
      specialGoodsList: [],
      shoNewPeopleZone: true,
      typeList: [
        {
          name: '积分',
          icon: '/static/image/main_jifen_icon.png',
          url: '',
        },
        {
          name: '券包',
          icon: '/static/image/main_coupon_icon.png',
          url: '/pageShopping/coupon/receivedList',
        },
        {
          name: '兑换中心',
          icon: '/static/image/main_change_icon.png',
          url: '',
        },
        {
          name: '签到',
          icon: '/static/image/main_sign_icon.png',
          url: '',
        },
      ],

      //二维码  使用变量
      ifShow: true,

      warehouseInfo: {},
      longitude: null,
      latitude: null,
      showTip: false,
      showQrCode: false,
      codeImg: '',
      immersive: true,
      titleColor: '#fff',
    }
  },
  onShow() {
    this.getGoodsType()
    this.getRecommendGoods()
    const data = getUserInfo()
    this.user = JSON.parse(data)
    if (this.user && this.user.customerIds) {
      this.customerId = this.user.customerIds
    }
    // if (this.customerId) {
    //   this.showQrCode = true

    // } else {
    //   this.showQrCode = false
    // }
    if (!this.warehouseInfo.id) {
      this.getLocation()
    }
    // this.goCitizenCard()
  },
  onPageScroll(e) {
    // 根据滚动位置改变导航栏背景
    if (e.scrollTop > 50) {
      this.immersive = false
      this.titleColor = '#333'
    } else {
      this.immersive = true
      this.titleColor = '#fff'
    }
  },
  onPullDownRefresh() {
    this.getGoodsType()
    this.getRecommendGoods()
    this.customerId = this.user.customerIds
    if (this.customerId) {
      if (!this.warehouseInfo.id) {
        this.getLocation()
      }
      uni.stopPullDownRefresh()
    }
  },
  // 监听用户点击右上角菜单的「转发」按钮时触发的事件
  onShareAppMessage() {},
  // 分享到朋友圈
  onShareTimeline(res) {},
  // 收藏
  onAddToFavorites(res) {},
  async created() {
    //获取推荐商品
    const app = getApp()
    const data = await getUserInfo()
    this.user = JSON.parse(data)
    console.log('home,user', this.user)
    //不管有没有信息，都自动登录
    await this.goWechatLogin()
    // this.user = JSON.parse(getUserInfo())

    this.getWxOpenId()
    if (this.user && this.user.customerIds) {
      this.customerId = this.user.customerIds
    }
  },
  computed: {
    ...mapState({
      cartItems: state => state.cart.cartItems,
    }),
  },
  methods: {
    ...mapMutations('cart', ['updateGoodsCount', 'removeFromCart', 'toggleSelect', 'addToCart']),
    getLocation() {
      const that = this
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        isHighAccuracy: true,
        success: function (res) {
          // that.showTip = false
          that.longitude = res.longitude
          that.latitude = res.latitude
          that.getBaseWareList() //获取自提点
          console.log('当前位置的经度：' + res.longitude)
          console.log('当前位置的纬度：' + res.latitude)
        },
        fail: function (err) {
          that.showTip = true
        },
      })
    },
    async getWxCode() {
      return new Promise((resolve, reject) => {
        wx.login().then(res => {
          resolve(res.code)
        })
      })
    },
    async goWechatLogin() {
      const that = this
      that.uniShowLoading()
      const companyCode = '000'
      const wxCode = await this.getWxCode()
      const res = await wxLogin({ code: wxCode, companyCode }).catch(err => {
        that.uniHideLoading()
        // that.uniShowToast(err.msg)
      })
      console.log('res', res)
      this.uniHideLoading()
      const {
        status,
        data: { token, user },
      } = res
      console.log('status', status)
      if (status == 200) {
        setToken(token)
        setUserInfo(user)
        return new Promise((resolve, reject) => {
          resolve(status)
        })
      }
    },
    getBaseWareList() {
      const params = {
        page: 1,
        size: 100,
        lng: this.longitude,
        lat: this.latitude,
      }

      getBasWarehouseList(params).catch(err => {
        if (err.content.length > 0) {
          this.warehouseInfo = err.content[0]
        }
      })
    },
    showPop() {
      this.$refs.popup.open()
    },
    getGoodsType() {
      getBasGoodsTypeTree({ size: 999, sort: 'seq asc' })
        .then(res => {
          console.log('goodType success' + JSON.stringify(res))
        })
        .catch(res => {
          console.log('apiBaseUrl', apiBaseUrl)

          res = res.sort((a, b) => a.seq - b.seq)
          this.goodsTypeList = res.slice(0, 3)
          this.goodsTypeList = this.goodsTypeList.map(item => {
            return { ...item, imageUrl: this.isExternalLink(item.imageUrl) ? item.imageUrl : apiBaseUrl + item.imageUrl }
          })
          const more = { name: '更多', imageUrl: require('@/static/image/main_more.png') }
          this.goodsTypeList.push(more)
          console.log('goodsTypeList', this.goodsTypeList)
        })
    },
    draw() {
      const couponIds = this.unCollectCouponList.map(item => item.id).join(',')
      uni.showLoading({ title: '获取中' })
      collect({ customerId: this.customerId, couponIds })
        .then(res => {
          uni.showToast({ title: '领取成功', icon: 'none' })
          this.showCouponBox = false
          uni.hideLoading()
        })
        .catch(err => {
          uni.showToast({ title: err.msg, icon: 'none', duration: 2000 })
          uni.hideLoading()
        })
    },

    // getCustomerUnCollectCouponList() {
    //   customerUnCollectCouponList({ customerId: this.customerId }).catch(err => {
    //     this.unCollectCouponList = err.content
    //     if (this.unCollectCouponList.length > 0) {
    //       this.showCouponBox = true
    //     }
    //   })
    // },
    // getDict() {
    //   getDict({ dictCode: 'dict_applet_is_show_new_people_zone' }).catch(res => {
    //     this.shoNewPeopleZone = res.content[0].value === '1'
    //   })
    // },
    async getWxOpenId() {
      const _that = this
      const wxCode = await this.getWxCode()
      getLoginOpenId({ code: wxCode, companyCode: '000' }).then(val => {
        if (val.status === 200) {
          console.log(`当前获取openid为${val.data.openid}`)
          setOpenId(val.data.openid, '000')
          setSessionKey(val.data.session_key)
        }
      })
    },
    jumpNotice() {
      uni.navigateTo({ url: '/pages/notice/index' })
    },
    jumpSearch(e, params = null) {
      if (this.customerId === null || this.customerId === '' || this.customerId === undefined) return uni.showToast({ title: '请先选择客户', icon: 'none' })
      let url = '/pageShopping/search/index'
      if (params) {
        url += `?params=${JSON.stringify(params)}`
      }
      uni.navigateTo({ url })
    },

    getRecommendGoods() {
      uni.showLoading({ title: '加载中' })
      const data = {
        // customerId: this.customerId,
        ...this.query,
      }
      basGoodsListForAdd(data).catch(err => {
        uni.hideLoading()
        if (err.content) {
          this.recommendGoods = err.content
          this.recommendGoods.forEach(item => {
            if (item.mainImage && item.mainImage !== 'null') {
              item.image = item.mainImage
            } else {
              item.image = 'https://www.zjjqf.cn/file/static/undefined.png'
            }
          })
        }
      })
    },
    jumpShopping(item) {
      uni.navigateTo({ url: `/pageShopping/home/index?typeId=${item.id}` })
    },
    goRegister() {
      uni.navigateTo({
        url: `/pages/register/index`,
      })
    },

    goDetail(item) {
      if (item.url) {
        uni.navigateTo({ url: item.url })
      } else {
        this.uniShowToast('暂未开放')
      }
    },
    receiveCoupon() {
      uni.navigateTo({ url: '/pageShopping/coupon/unreceivedList' })
    },
    goShop(item) {
      getApp().globalData.goodType = item
      uni.switchTab({
        url: '/pages/shopping/index',
      })
    },
    selectGoods(item, goodsCount) {
      //加入购物车
      console.log('goodCount', goodsCount)
      const existingItem = this.recommendGoods.find(_item => _item.goodsId === item.goodsId)
      if (existingItem) {
        existingItem.goodsCount = goodsCount ? goodsCount : existingItem.goodsCount + 1
        this.$store.commit('addToCart', existingItem)
        this.uniShowToast('已加入购物车')
      }
    },
    operateCount(params) {
      //购物车加减 from:是从购物车还是列表页返回
      console.log('index operateCount', params)
      const { item, type } = params
      const existingItem = this.recommendGoods.find(_item => _item.goodsId === item.goodsId)

      if (type === 'add') {
        const count = item.goodsCount + 1
        this.$store.commit('updateGoodsCount', { goodsId: item.goodsId, goodsCount: count })
        if (existingItem) {
          existingItem.goodsCount = count
        }
      } else if (type === 'del') {
        if (item.goodsCount >= 2) {
          const count = item.goodsCount - 1
          this.$store.commit('updateGoodsCount', { goodsId: item.goodsId, goodsCount: count })
          if (existingItem) {
            existingItem.goodsCount = count
          }
        } else {
          //弹框是否删除该商品
          uni.showModal({
            content: '确定要删除该商品么',

            success: res => {
              if (res.confirm) {
                //删除
                this.$store.commit('removeFromCart', item.goodsId)
                if (existingItem) {
                  existingItem.goodsCount = 0
                }
              } else if (res.cancel) {
              }
            },
          })
        }
      }
    },

    goItemDetail(item) {
      uni.navigateTo({ url: `/pageShopping/detail/index?item=` + encodeURIComponent(JSON.stringify(item)) })
    },
    goWarehouse() {
      const _that = this
      uni.navigateTo({
        url: '/pageShopping/warehouse/index',
        events: {
          // 选择自提点，返回选中的自提点

          acceptDataFromOpenedPage: function (data) {
            console.log('back', data)
            if (data) {
              _that.warehouseInfo = data
            }
          },
        },
      })
    },
    getQR() {
      const _this = this
      //生成小程序二维码
      const data = {
        path: `/pages/register/index?userId=${this.user.userId}`,
        companyCode: '000',
      }
      getQRCode(data).then(res => {
        // console.log('获取二维码',res)
        //   let base64 = wx.arrayBufferToBase64(res.data.qr_code)

        this.codeImg = 'data:image/PNG;base64,' + res.data.qr_code
        // console.log('二维码',this.codeImg)
      })
    },
    /**
     * 保存Base64图片到相册
     * @param {string} base64Data 不带前缀的纯Base64数据
     */
    async saveBase64ToPhotosAlbum() {
      const result = await SaveImageUtil.saveBase64ToAlbum(this.codeImg)
      if (result.success) {
        uni.showToast({ title: result.message, icon: 'success' })
      } else {
        uni.showToast({ title: result.message, icon: 'none' })
      }
    },
    getImage(item) {
      if (condition) {
      }
    },
    goCitizenCard() {
      this.goCitizen(this.user.userId)
    },
  },
}
</script>

<style lang="scss" scoped>
page {
  background-color: #f6f6f6 !important;
}
.container {
  width: 100vw;
  height: 100vh;

  background-image: url('https://bw000.zjjqf.cn/file/000upload/image/home_bg.png');
  background-repeat: no-repeat;
  background-size: cover;

  &_bg {
    height: 100vh;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
  &_header {
    &_location {
      margin: 0 20rpx;
      display: flex;
      align-items: center;
      &_name {
        font-size: 32rpx;
        color: white;
        font-weight: bold;
        margin: 0 30rpx 0 10rpx;
      }
    }
  }
  &_type-btn {
    width: 120rpx;
    margin: 240rpx 20rpx 30rpx 35rpx;
  }
  &_middle {
    background-color: white;
    margin: 20rpx;
    padding: 30rpx 0;
    border-radius: 16rpx;
    &_row {
      display: flex;
      justify-content: space-between;

      &_item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        &_icon {
          width: 60rpx;
          height: 60rpx;
          margin-bottom: 10rpx;
        }
        &_categry {
          width: 120rpx;
          height: 120rpx;
          image {
            margin-bottom: 10rpx;
            width: 112rpx;
            height: 112rpx;
            border-radius: 110rpx;
            box-shadow: 0 5px 3px 0 rgba(196, 196, 196, 0.55);
          }
        }
      }
    }
  }

  &_pic-2 {
    margin: 10rpx 20rpx;
  }
  &_scan {
    display: flex;
    align-items: center;
    background: linear-gradient(to right, #f8ebca, #ffdd93);
    padding: 0 20rpx;
    margin: 20rpx;
    border-radius: 10rpx;
    &_qr-code {
      width: 150rpx;
      height: 150rpx;
      background-color: white;
      padding: 8rpx;
      margin: 10rpx 0;
      border-radius: 10rpx;
    }
    &_title {
      flex: 3;
      padding-right: 50rpx;
      margin: 0 20rpx;
      image {
        width: 200rpx;
      }
    }
    &_bag {
      width: 120rpx;
    }
  }
  &_coupon {
    margin: 20rpx 20rpx 20rpx 20rpx;
  }
  &_recommand {
    margin: 30rpx 0;
    padding: 0 10rpx;
    &_pic {
      width: 196rpx;
      margin-left: 20rpx;
      margin-bottom: 20rpx;
    }
    &_item {
      flex: 1;
      background-color: white;
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      /* align-items: center; */
      margin: 0 10rpx;
      padding-bottom: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      &_pic {
        width: 100%;
        height: 340rpx;

        image {
          width: 100%;
          height: 100%;
          border-top-left-radius: 16rpx;
          border-top-right-radius: 16rpx;
        }
      }
      &_title {
        margin: 10rpx 20rpx;
        text-align: left;
      }
      &_money {
        width: 100%;
        display: flex;
        padding: 0 20rpx;
        align-items: center;
        justify-content: space-between;
        image {
          width: 45rpx;
        }
      }
    }
  }
}
.pop-pic {
  width: 300rpx;
}
</style>
